package com.cuit.service.impl;

import com.cuit.mapper.ArticleMapper;
import com.cuit.mapper.UserMapper;
import com.cuit.pojo.Article;
import com.cuit.pojo.User;
import com.cuit.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    UserMapper userMapper;
    public List<Article> findAll(int page,int pageSize){
        List<Article> list = articleMapper.findAll((page-1)*pageSize,pageSize);
        for (Article article:list){
            article.setUserName(userMapper.findById(article.getUserId()).getName());
            article.setUserHead(userMapper.findById(article.getUserId()).getHead());
        }
        return list;
    }
    public int countAll(){
        return articleMapper.countAll();
    }

    public List<Article> search(int page, int pageSize, String searchText) {
        System.out.println(searchText);
        if (searchText==null)
            return articleMapper.findAll((page-1)*pageSize,pageSize);
        return articleMapper.findArticleLikeSearchText((page-1)*pageSize,pageSize,searchText);
    }

    public List<Article> findArticleByUserId(int userId,int page,int pageSize){
        return articleMapper.findArticleByUserId(userId,page,pageSize);
    }
    public int countArticleByUserId(){
        return articleMapper.countArticleByUserId();
    }
    public Article findArticleById(int articleId){
        return articleMapper.findById(articleId);
    }
    public void likeById(int id){
        Article article=articleMapper.findById(id);
        int like = article.getLikeNum()+1;
        article.setLikeNum(like);
        articleMapper.updateById(article);
    }
    public void dislikeById(int id){
        Article article=articleMapper.findById(id);
        int dislike = article.getDislikeNum()+1;
        article.setDislikeNum(dislike);
        articleMapper.updateById(article);
    }
    public void insertArticle(int userId, String articleTitle, String articleText){
        Article article = new Article();
        User user = userMapper.findById(userId);
        article.setText(articleText);
        article.setTitle(articleTitle);
        article.setUserId(userId);
        article.setCreatedDate(LocalDate.now());
        article.setLikeNum(0);
        article.setDislikeNum(0);
        article.setClickNum(0);
        article.setUserHead(user.getHead());
        article.setUserName(user.getName());
        articleMapper.insertArticle(article);
    }
}
